<template>
	<view class="fill-width-height">
		<canvas canvas-id="saveCanvas" id="saveCanvas" type="2d" :style="{'width':canWidth+'px','height':canHeight+'px','left':canvasLeft+'rpx'}"
			style="border: 2px solid green;position: absolute;top:0px;" />
	</view>
</template>

<script>
	let canvas, canvasBgColor, dpr, ctx, arrayInfo
	let curIndex = 0
	export default {
		name: "tk-view2img",
		data() {
			return {
				canWidth: 100,
				canHeight: 100
			};
		},
		props: {
			canvasLeft:{
				type: Number,
				default: 10000
			},
			saveId:{
				type: String,
				default: () => ''
			}
		},
		watch: {
			saveId: {
				handler(val) {
					if (val?.length > 0) {
						this.savePic();
					}
				},
				immediate: true,
				deep: false
			},
		},
		methods: {
			async savePic() {
				curIndex = 0
				// 查询绘制信息
				const queryInfo = await this.queryInfo()
				console.log(queryInfo)
				console.log('arrayInfo', arrayInfo)
				// 初始化画布
				const initCanvas = await this.initCanvas()
				console.log(initCanvas)
				// 绘制其他信息
				for (let i = 0; i < arrayInfo.length; i++) {
					const res = await this.drawOther()
					console.log('res: ',res)
				}
				// curIndex = 1
				const that = this
				uni.canvasToTempFilePath({
					canvasId: "saveCanvas",
					canvas: canvas,
					success: function(res) {
						uni.hideLoading()
						console.log("tempFilePath： ", res.tempFilePath)
						that.$emit('resFilePath', res.tempFilePath)
						// wx.showShareImageMenu({
						// 	path:res.tempFilePath
						// })
					}
				})
			},
			//查询绘制信息
			queryInfo() {
			    return new Promise((resolve) => {
			        uni.createSelectorQuery().selectAll(".drawInfo").boundingClientRect().exec((res) => {
			            arrayInfo = res[0].map((item, index) => {
			                if (!item.dataset["index"]) {
			                    item.dataset["index"] = index;
			                }
			                return item;
			            }).sort((a, b) => {
			                // 修改排序逻辑，将 b 的 data-index 减去 a 的 data-index
			                return b.dataset["index"] - a.dataset["index"];
			            });
			            resolve("绘制信息已查询");
			        });
			    });
			},
			// queryInfo() {
			// 	return new Promise((resolve) => {
			// 		uni.createSelectorQuery().selectAll('.drawInfo').boundingClientRect().exec((res) => {
			// 			arrayInfo = res[0]
			// 			resolve('绘制信息已查询')
			// 		})
			// 	})
			// },
			//初始化canvas
			initCanvas() {
				return new Promise((resolve) => {
					uni.createSelectorQuery().in(this).select("#saveCanvas")
						.fields({
							node: true,
							size: true
						}).exec((res) => {
							canvas = res[0].node;
							ctx = canvas.getContext('2d');
							dpr = uni.getWindowInfo().pixelRatio;
							this.canWidth = arrayInfo[0].width;
							this.canHeight = arrayInfo[0].height;
			
							canvas.width = this.canWidth * dpr;
							canvas.height = this.canHeight * dpr;
			
							ctx.scale(dpr, dpr);
							// 设置背景透明
							ctx.fillStyle = 'rgba(0, 0, 0, 0)'; 
							ctx.clearRect(0, 0, canvas.width, canvas.height);
							// 若干绘制调用
							ctx.fillRect(0, 0, canvas.width, canvas.height);
							resolve('画布初始化完成');
							
							// canvas = res[0].node
							// ctx = canvas.getContext('2d')
							// dpr = uni.getWindowInfo().pixelRatio
							// this.canWidth = arrayInfo[0].width
							// this.canHeight = arrayInfo[0].height

							// canvas.width = this.canWidth * dpr
							// canvas.height = this.canHeight * dpr

							// ctx.scale(dpr, dpr)
							// ctx.fillStyle = arrayInfo[0].dataset.bgcolor
							// ctx.clearRect(0, 0, canvas.width, canvas.height)
							// // 若干绘制调用
							// ctx.fillRect(0, 0, canvas.width, canvas.height)
							// resolve('画布初始化完成')
						})
				})
			},
			//绘制其他view
			drawOther() {
				return new Promise((resolve) => {
					// 判断是否是图片
					if (arrayInfo[curIndex].dataset.type == 'img') {
						const image = canvas.createImage()
						image.onload = () => {
							ctx.drawImage(
								image,
								arrayInfo[curIndex].left - arrayInfo[0].left,
								arrayInfo[curIndex].top - arrayInfo[0].top,
								arrayInfo[curIndex].width,
								arrayInfo[curIndex].height
							)
							curIndex++
							resolve('图片已绘制')
						}
						if(arrayInfo[curIndex].dataset.src){
							image.src = arrayInfo[curIndex].dataset.src
						}
					}
					else if(arrayInfo[curIndex].dataset.type == 'text'){
						const left = arrayInfo[curIndex].left- arrayInfo[0].left
						const top = arrayInfo[curIndex].top - arrayInfo[0].top
						ctx.fillStyle = arrayInfo[curIndex].dataset.color
						ctx.textBaseline = "top"
						let fontSize = this.rpxtopx(arrayInfo[curIndex].dataset.size)
						ctx.font = fontSize.toString() + "px sans-serif"
						ctx.fillText(arrayInfo[curIndex].dataset.word, left, top)
						curIndex++
						resolve('文字已绘制');
					}
					else if(arrayInfo[curIndex].dataset.type == 'view'){
						const left = arrayInfo[curIndex].left- arrayInfo[0].left
						const top = arrayInfo[curIndex].top - arrayInfo[0].top
						ctx.fillStyle = arrayInfo[curIndex].dataset.bgcolor
						ctx.fillRect(left, top, arrayInfo[curIndex].width, arrayInfo[curIndex].height)
						curIndex++
						resolve('view已绘制');
					}
					else{
						resolve('无绘制数据')
					}

				})
			},
			rpxtopx(rpx) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
				let px = (deviceWidth / 750) * Number(rpx)
				return Math.floor(px);
			},
		}
	}
</script>

<style scoped>
	.higher-z-index {
		z-index: 101; 
	}
</style>